// 暴力破解法
var maxProfit = function (prices) {
  let maxPrice = -1;
  let len = prices.length;
  for (let i = 0; i < len; i++) {
    let max = prices[i];
    let min = prices[i];
    for (let j = i; j < len; j++) {
      if (max < prices[j]) {
        max = prices[j];
      }
    }

    if (max - min > maxPrice) {
      maxPrice = max - min;
    }
  }
  if (maxPrice > 0) {
    return maxPrice;
  } else {
    return 0;
  }
};

// 一次遍历法
var maxProfit1 = function (prices) {
  let minPrice = Infinity;
  let max = 0;
  let len = prices.length;
  for (let i = 0; i < len; i++) {
    if (prices[i] < minPrice) {
      minPrice = prices[i];
    } else if (prices[i] - minPrice > max) {
      max = prices[i] - minPrice;
    }
  }
  return max;
};

let prices1 = [7, 1, 5, 3, 6, 4];
let prices2 = [7, 6, 4, 3, 1];
let prices3 = [2, 4, 1];

console.log(maxProfit(prices1));
